package com.biquge.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.biquge.common.CommonUtils;
import com.biquge.common.CustomException;
import com.biquge.common.ThreadPoolUtils;
import com.biquge.dao.NovelCopyDao;
import com.biquge.dao.NovelDao;
import com.biquge.entity.Novel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wangmeng
 * @since 2021/12/11
 */
@Service
@Slf4j
public class NovelService {

    @Autowired
    NovelDao novelDao;
    @Autowired
    NovelCopyDao novelCopyDao;


    public void startDownload(String url) {
        int i = StringUtils.lastIndexOf(url, "/");
        String start = StringUtils.substring(url, i + 1);
        String body = StringUtils.substring(url, 0, i + 1);
        novelReptile novelReptile = new novelReptile(0, "",novelDao,novelCopyDao,0);
        String novelName = CommonUtils.getFromIndex(url );
        List<Novel> novels = novelDao.selectList(new LambdaQueryWrapper<Novel>().eq(Novel::getNovelName, novelName));
        if(CollectionUtils.isNotEmpty(novels)){
            if(!"获取失败!".equals(novels.get(0).getStatus())){
                throw new CustomException("该小说正在获取！");
            }
        }
        ThreadPoolUtils.run(() -> novelReptile.getFromIndex(body, start,novelName));
    }


}
